package com.calm.clibrary.andswipeback;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import java.util.LinkedList;
import java.util.List;

/**
 * Create by Calm
 * 2020/1/11 11:10
 * Activity生命周期管理类
 * 要接收Activity各生命周期，需在Application中注册
 * 使用方法在Application onCreate()中registerActivityLifecycleCallbacks(ActivityLifecyleHelper.getInstance());
 */
public class AndActivityLifecyleHelper implements Application.ActivityLifecycleCallbacks {
    private static AndActivityLifecyleHelper mInstance;
    private List<Activity> mActivitys;
    private AndActivityLifecyleHelper(){
        mActivitys = new LinkedList<>();
    }
    public static AndActivityLifecyleHelper getInstance(){
        if(mInstance == null){
            synchronized (AndActivityLifecyleHelper.class){
                mInstance = new AndActivityLifecyleHelper();
            }
        }
        return mInstance;
    }
    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
        addActivity(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        if(mActivitys == null){
            return;
        }
        if(mActivitys.contains(activity)){
            mActivitys.remove(activity);
        }
        if(mActivitys.isEmpty()){
            mActivitys = null;
        }
    }

    /**
     * 将Activity添加到List
     * @param activity
     */
    private void addActivity(Activity activity){
        if(mActivitys == null){
            mActivitys = new LinkedList<>();
        }
        mActivitys.add(activity);
    }

    /**
     * 获取前一个Activity的实例
     * @return
     */
    public Activity getPreviousActivity(){
        if(mActivitys == null || mActivitys.isEmpty()){
            return null;
        }
        int count = mActivitys.size();
        if(count < 2){
            return null;
        }
        return mActivitys.get(count - 2);
    }
}
